/** 
 * 渠道结算
 */
import moment from 'moment'
import riskApi from '@/config/server/api/risk'
import dt from '@dt/dt'

// 合作类型
let cooperationType = []
getCooperationType()

function list(params) {
  return riskApi.channelCount.list.fetch(params).then(res => {
    res.list = res.list.map(i => {
      let cooperationTypeName = ''
      if (cooperationType.find(o => o.key == i.cooperationType)) {
        cooperationTypeName = cooperationType.find(o => o.key == i.cooperationType).value
      }
      return {
        ...i,
        cooperationTypeName,
      }
    })
    return res
  })
}

// 修改渠道结算
function update({ calculateId, channelCost, thisAmount }) {
  return riskApi.channelCount.update.fetch({
    calculateId,
    channelCost,
    thisAmount
  }).then(res => {
    return res
  })
}

// 结算记录
function record(calculateId) {
  return riskApi.channelCount.record.fetch({
    calculateId
  }).then(res => {
    let data = res.map(i => ({
      ...i,
      calculateDate: i.calculateDate ? moment(i.calculateDate).format('YYYY-MM-DD') : ''
    }))
    return data
  })
}

// 处理列表传递的日期参数
function dealDate(key, options, index) {
  return options[key] && options[key][index] ? moment(options[key][index]).format('YYYY-MM-DD') : null
}

// 处理金额
function dealPrice(val) {
  let price = Number(val).toFixed()
  return price.indexOf('.') < 0 ? `${price}.00` : price
}

// 合作类型 list
function getCooperationType() {
  cooperationType = dt.dictInfo().channelType.reduce((arr, { children }) => {
    if (children) {
      for (let item of children) {
        if (!arr.find(i => i.key == item.key)) {
          arr.push({ key: item.key, value: item.value })
        }
      }
    }
    return arr
  }, [{ key: '', value: '无' }])
}

export default {
  list,
  update,
  record,
  
  dealDate,
}
